#!/bin/bash

# Tiny QA - 快速启动脚本
# 自动挂载文档目录并启动容器

set -e

echo "🚀 Tiny QA - 快速启动"
echo "========================================"

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker"
    exit 1
fi

# 容器配置
CONTAINER_NAME="tiny-qa"
IMAGE_NAME="tiny-qa:latest"
PORT="5002"

# 检查镜像是否存在
if ! docker images | grep -q "tiny-qa.*latest"; then
    echo "❌ 镜像不存在，请先构建镜像:"
    echo "  ./scripts/docker-build-fast.sh"
    exit 1
fi

# 停止并删除旧容器
if docker ps -a | grep -q "$CONTAINER_NAME"; then
    echo "🔄 停止旧容器..."
    docker stop "$CONTAINER_NAME" 2>/dev/null || true
    docker rm "$CONTAINER_NAME" 2>/dev/null || true
fi

# 获取文档目录路径
echo "📁 请选择文档目录挂载方式:"
echo "1. 使用默认路径: /path/to/your/documents"
echo "2. 手动输入路径"
echo "3. 跳过文档挂载（仅测试）"
echo ""
read -p "请选择 (1-3): " choice

case $choice in
    1)
        DOCS_PATH="/path/to/your/documents"
        ;;
    2)
        read -p "请输入文档目录路径: " DOCS_PATH
        ;;
    3)
        DOCS_PATH=""
        ;;
    *)
        echo "❌ 无效选择"
        exit 1
        ;;
esac

# 构建启动命令
if [ -n "$DOCS_PATH" ]; then
    if [ ! -d "$DOCS_PATH" ]; then
        echo "❌ 文档目录不存在: $DOCS_PATH"
        exit 1
    fi
    echo "📁 挂载文档目录: $DOCS_PATH"
    docker run -d \
        --name "$CONTAINER_NAME" \
        -p "$PORT:5002" \
        -v "$DOCS_PATH:/app/data/documents" \
        "$IMAGE_NAME"
else
    echo "⚠️  跳过文档挂载"
    docker run -d \
        --name "$CONTAINER_NAME" \
        -p "$PORT:5002" \
        "$IMAGE_NAME"
fi

# 检查容器启动状态
echo ""
echo "⏳ 等待容器启动..."
sleep 5

if docker ps | grep -q "$CONTAINER_NAME"; then
    echo "✅ 容器启动成功！"
    echo ""
    echo "📋 容器信息:"
    docker ps --filter "name=$CONTAINER_NAME" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
    echo ""
    echo "🌐 访问地址:"
    echo "  http://localhost:$PORT"
    echo ""
    echo "🔍 查看日志:"
    echo "  docker logs -f $CONTAINER_NAME"
    echo ""
    echo "📊 检查模型状态:"
    echo "  ./scripts/check-models.sh"
    echo ""
    echo "💡 提示:"
    echo "  - 首次启动需要下载AI模型，请耐心等待"
    echo "  - 模型下载完成后即可正常使用"
    echo "  - 使用 Ctrl+C 停止查看日志"
else
    echo "❌ 容器启动失败！"
    echo "查看错误日志:"
    docker logs "$CONTAINER_NAME"
    exit 1
fi 